package com.duowei.diandan.db.converter;

import android.arch.persistence.room.TypeConverter;
import android.text.TextUtils;
import android.util.Log;

import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormat;

public class Converters {
    private static final String TAG = "Converters";

    @TypeConverter
    public static LocalDateTime string2LocalDateTime(String s) {
        return TextUtils.isEmpty(s) ? null : new LocalDateTime(s);
    }

    @TypeConverter
    public static String localDateTime2String(LocalDateTime ldt) {
        return ldt == null ? null : ldt.toString();
    }

    // -----

    @TypeConverter
    public static LocalDate string2LocalDate(String s) {
        if (TextUtils.isEmpty(s)) {
            return null;
        } else {
            try {
                return DateTimeFormat.forPattern("yyyy-MM-dd").parseLocalDate(s);

            } catch (UnsupportedOperationException|IllegalArgumentException e) {
                Log.e(TAG, "string2LocalDate: ", e);

                return null;
            }
        }
    }

    @TypeConverter
    public static String localDate2String(LocalDate ld) {
        return ld == null ? null : ld.toString("yyyy-MM-dd");
    }

    // -----

    @TypeConverter
    public static LocalTime string2LocalTime(String s) {
        if (TextUtils.isEmpty(s)) {
            return null;
        } else {
            try {
                return DateTimeFormat.forPattern("HH:mm").parseLocalTime(s);

            } catch (UnsupportedOperationException|IllegalArgumentException e) {
                Log.e(TAG, "string2LocalTime: ", e);

                return null;
            }
        }
    }

    @TypeConverter
    public static String localTime2String(LocalTime lt) {
        return lt == null ? null : lt.toString("HH:mm");
    }
}
